const QQMapWX = require('../../qqmap-wx-jssdk.js')

// pages/index1/index1.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    movies: [],
    active: '1', //用户保存当前选中的类别ID
    cityname:''
  },
  tapNav(e) {
    let id = e.target.dataset.id
    this.setData({
      active: id
    })
    wx.getStorage({
      key: id,
      success: (data) => {
        console.log('从缓存中得到:', data)
        this.setData({
          movies: data.data
        })
      },
      fail: (err) => {
        console.log('读取缓存失败')
        this.loadMovies(id, 0).then(data => {
          this.setData({
            movies: data
          })
          wx.setStorage({
            key: id,
            data: data
          })
        })
      }
    })

  },
  loadMovies(cid, offset) {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '正在加载中...',
        mask: true
      })
      wx.request({
        url: 'https://api.tedu.cn/index.php',
        method: 'GET',
        data: {
          cid,
          offset
        },
        success: (res) => {
          resolve(res.data)
        },
        fail: (err) => {
          reject(err)
        },
        complete: () => {
          wx.hideLoading()
        }
      })
    })
  },
  getLocation() {
    //加载腾讯位置服务
    let QQMapSDK = require('../../qqmap-wx-jssdk.js')
    let qqmapsdk = new QQMapWX({
      key: 'MLYBZ-BSWLD-ZXI4U-PH44I-6TRDO-ERBAV'
    })
    qqmapsdk.reverseGeocoder({
      success:(res)=>{
        let city=res.result.address_component.city
        console.log('当前地址',city)
        this.setData({cityname:city})
        
        
      },
      fail:(err)=>{
        console.warn('地址检索失败',err)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    //加载当前位置信息 显示在页面左上角
    this.getLocation()
    this.loadMovies(1, 0).then(data => {
      this.setData({
        movies: data
      })
    })
  },
  onReachBottom() {
    console.log('到底了')
    let cid = this.data.active
    let offset = this.data.movies.length
    this.loadMovies(cid, offset).then(data => {
      this.setData({
        movies: this.data.movies.concat(data)
      })
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    console.log('下拉刷新...')
    let id = this.data.active
    this.loadMovies(id, 0).then(data => {
      this.setData({
        movies: data
      })
      wx.setStorage({
        key: id,
        data: data
      })
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})